<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图文编辑器 - 杂志管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        .editor-container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            min-height: 100vh;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }

        .editor-header {
            background: #2c3e50;
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .editor-title {
            font-size: 24px;
            font-weight: bold;
        }

        .editor-actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #3498db;
            color: white;
        }

        .btn-success {
            background: #27ae60;
            color: white;
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .editor-toolbar {
            background: #34495e;
            padding: 15px 20px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: center;
        }

        .toolbar-group {
            display: flex;
            gap: 5px;
            align-items: center;
            padding: 0 10px;
            border-right: 1px solid #4a5f7a;
        }

        .toolbar-group:last-child {
            border-right: none;
        }

        .toolbar-btn {
            background: #4a5f7a;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .toolbar-btn:hover {
            background: #5a6f8a;
        }

        .toolbar-btn.active {
            background: #3498db;
        }

        .editor-content {
            display: flex;
            min-height: calc(100vh - 140px);
        }

        .editor-sidebar {
            width: 300px;
            background: #ecf0f1;
            padding: 20px;
            border-right: 1px solid #ddd;
        }

        .sidebar-section {
            margin-bottom: 25px;
        }

        .sidebar-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }

        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .form-textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            resize: vertical;
            min-height: 80px;
        }

        .editor-main {
            flex: 1;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }

        .editor-workspace {
            background: white;
            border: 1px solid #ddd;
            border-radius: 5px;
            min-height: 600px;
            padding: 30px;
            font-size: 16px;
            line-height: 1.8;
            outline: none;
            overflow-y: auto;
            max-height: 600px;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
            transition: box-shadow 0.3s ease;
        }

        .editor-workspace:focus {
            border-color: #3498db;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.3), inset 0 2px 4px rgba(0,0,0,0.1);
        }

        .editor-workspace:focus {
            border-color: #3498db;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.3);
        }

        .editor-workspace::-webkit-scrollbar {
            width: 8px;
        }

        .editor-workspace::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .editor-workspace::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .editor-workspace::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        .image-upload-area {
            border: 2px dashed #3498db;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            margin: 20px 0;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }

        .image-upload-area:hover {
            background: #e3f2fd;
            border-color: #2980b9;
        }

        .image-upload-area.dragover {
            background: #bbdefb;
            border-color: #1976d2;
        }

        .upload-icon {
            font-size: 48px;
            color: #3498db;
            margin-bottom: 15px;
        }

        .upload-text {
            font-size: 16px;
            color: #666;
            margin-bottom: 15px;
        }

        .image-preview {
            max-width: 100%;
            margin: 20px 0;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .article-list {
            background: white;
            border-radius: 5px;
            overflow: hidden;
        }

        .article-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        .article-item:hover {
            background: #f8f9fa;
        }

        .article-item:last-child {
            border-bottom: none;
        }

        .article-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
            color: #2c3e50;
        }

        .article-meta {
            font-size: 12px;
            color: #7f8c8d;
        }

        .status-bar {
            background: #34495e;
            color: white;
            padding: 10px 20px;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .progress-bar {
            width: 200px;
            height: 4px;
            background: #4a5f7a;
            border-radius: 2px;
            overflow: hidden;
            display: none;
        }

        .progress-fill {
            height: 100%;
            background: #3498db;
            width: 0%;
            transition: width 0.3s ease;
        }

        .message {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 5px;
            color: white;
            font-weight: bold;
            z-index: 1000;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        }

        .message.show {
            transform: translateX(0);
        }

        .message.success {
            background: #27ae60;
        }

        .message.error {
            background: #e74c3c;
        }

        @media (max-width: 768px) {
            .editor-content {
                flex-direction: column;
            }
            
            .editor-sidebar {
                width: 100%;
            }
            
            .editor-toolbar {
                padding: 10px;
                gap: 10px;
            }
            
            .toolbar-group {
                padding: 0 5px;
            }
        }
    </style>
</head>
<body>
    <div class="editor-container">
        <header class="editor-header">
            <div class="editor-title">📝 图文编辑器</div>
            <div class="editor-actions">
                <button class="btn btn-secondary" onclick="editor.newArticle()">新建文章</button>
                <button class="btn btn-primary" onclick="editor.saveArticle()">保存文章</button>
                <button class="btn btn-success" onclick="editor.previewArticle()">预览文章</button>
            </div>
        </header>

        <div class="editor-toolbar">
            <div class="toolbar-group">
                <button class="toolbar-btn" onclick="editor.formatText('bold')" title="加粗">B</button>
                <button class="toolbar-btn" onclick="editor.formatText('italic')" title="斜体">I</button>
                <button class="toolbar-btn" onclick="editor.formatText('underline')" title="下划线">U</button>
            </div>
            <div class="toolbar-group">
                <button class="toolbar-btn" onclick="editor.formatText('justifyLeft')" title="左对齐">⬅</button>
                <button class="toolbar-btn" onclick="editor.formatText('justifyCenter')" title="居中">⬌</button>
                <button class="toolbar-btn" onclick="editor.formatText('justifyRight')" title="右对齐">➡</button>
            </div>
            <div class="toolbar-group">
                <button class="toolbar-btn" onclick="editor.insertHeading()" title="标题">H</button>
                <button class="toolbar-btn" onclick="editor.insertParagraph()" title="段落">P</button>
                <button class="toolbar-btn" onclick="editor.insertList()" title="列表">☰</button>
            </div>
            <div class="toolbar-group">
                <button class="toolbar-btn" onclick="editor.insertImage()" title="插入图片">🖼️</button>
                <button class="toolbar-btn" onclick="editor.insertLink()" title="插入链接">🔗</button>
            </div>
        </div>

        <div class="editor-content">
            <aside class="editor-sidebar">
                <div class="sidebar-section">
                    <div class="sidebar-title">文章信息</div>
                    <div class="form-group">
                        <label class="form-label">文章标题</label>
                        <input type="text" class="form-input" id="articleTitle" placeholder="请输入文章标题">
                    </div>
                    <div class="form-group">
                        <label class="form-label">文章摘要</label>
                        <textarea class="form-textarea" id="articleSummary" placeholder="请输入文章摘要"></textarea>
                    </div>
                    <div class="form-group">
                        <label class="form-label">作者</label>
                        <input type="text" class="form-input" id="articleAuthor" placeholder="请输入作者名称">
                    </div>
                </div>

                <div class="sidebar-section">
                    <div class="sidebar-title">图片上传</div>
                    <div class="image-upload-area" id="imageUploadArea">
                        <div class="upload-icon">📷</div>
                        <div class="upload-text">拖拽图片到此处或点击上传</div>
                        <button class="btn btn-primary" onclick="editor.selectImage()">选择图片</button>
                        <input type="file" id="imageInput" accept="image/*" style="display: none;" onchange="editor.handleImageSelect(this.files)">
                    </div>
                </div>

                <div class="sidebar-section">
                    <div class="sidebar-title">文章列表</div>
                    <div class="article-list" id="articleList">
                        <div class="article-item" onclick="editor.loadArticle(1)">
                            <div class="article-title">示例文章标题</div>
                            <div class="article-meta">2024-01-15 | 未发布</div>
                        </div>
                    </div>
                </div>
            </aside>

            <main class="editor-main">
                <div class="editor-workspace" id="editorWorkspace" contenteditable="true">
                    <h1>开始编写您的文章...</h1>
                    <p>在这里输入文章内容，支持富文本编辑、图片插入等功能。</p>
                </div>
            </main>
        </div>

        <div class="status-bar">
            <div class="status-left">
                <span id="statusText">就绪</span>
            </div>
            <div class="status-right">
                <div class="progress-bar" id="progressBar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <span id="wordCount">字数: 0</span>
            </div>
        </div>
    </div>

    <script>
        class ArticleEditor {
            constructor() {
                this.currentArticle = null;
                this.articles = [];
                this.apiBase = 'http://localhost:8080/api';
                this.init();
            }

            init() {
                this.setupEventListeners();
                this.loadArticles();
                this.updateWordCount();
            }

            setupEventListeners() {
                const workspace = document.getElementById('editorWorkspace');
                const uploadArea = document.getElementById('imageUploadArea');

                // 编辑器内容变化监听
                workspace.addEventListener('input', () => {
                    this.updateWordCount();
                    this.autoSave();
                });

                // 拖拽上传
                uploadArea.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    uploadArea.classList.add('dragover');
                });

                uploadArea.addEventListener('dragleave', () => {
                    uploadArea.classList.remove('dragover');
                });

                uploadArea.addEventListener('drop', (e) => {
                    e.preventDefault();
                    uploadArea.classList.remove('dragover');
                    this.handleImageSelect(e.dataTransfer.files);
                });

                // 自动保存
                setInterval(() => this.autoSave(), 30000); // 30秒自动保存
            }

            formatText(command) {
                document.execCommand(command, false, null);
                document.getElementById('editorWorkspace').focus();
            }

            insertHeading() {
                const workspace = document.getElementById('editorWorkspace');
                const selection = window.getSelection();
                
                if (selection.rangeCount > 0) {
                    const range = selection.getRangeAt(0);
                    const h2 = document.createElement('h2');
                    h2.textContent = '标题 ';
                    h2.contentEditable = true;
                    
                    range.deleteContents();
                    range.insertNode(h2);
                    
                    // 将光标移到标题后面
                    range.setStartAfter(h2);
                    range.setEndAfter(h2);
                    selection.removeAllRanges();
                    selection.addRange(range);
                }
            }

            insertParagraph() {
                const workspace = document.getElementById('editorWorkspace');
                const selection = window.getSelection();
                
                if (selection.rangeCount > 0) {
                    const range = selection.getRangeAt(0);
                    const p = document.createElement('p');
                    p.textContent = '新段落 ';
                    p.contentEditable = true;
                    
                    range.deleteContents();
                    range.insertNode(p);
                    
                    range.setStartAfter(p);
                    range.setEndAfter(p);
                    selection.removeAllRanges();
                    selection.addRange(range);
                }
            }

            insertList() {
                const workspace = document.getElementById('editorWorkspace');
                const ul = document.createElement('ul');
                
                for (let i = 0; i < 3; i++) {
                    const li = document.createElement('li');
                    li.textContent = `列表项 ${i + 1}`;
                    li.contentEditable = true;
                    ul.appendChild(li);
                }
                
                workspace.appendChild(ul);
            }

            insertImage() {
                document.getElementById('imageInput').click();
            }

            insertLink() {
                const url = prompt('请输入链接地址:');
                if (url) {
                    const title = prompt('请输入链接标题:') || url;
                    document.execCommand('insertHTML', false, `<a href="${url}" target="_blank">${title}</a>`);
                }
            }

            selectImage() {
                document.getElementById('imageInput').click();
            }

            async handleImageSelect(files) {
                const validFiles = Array.from(files).filter(file => 
                    file.type.startsWith('image/')
                );

                if (validFiles.length === 0) {
                    this.showMessage('请选择有效的图片文件', 'error');
                    return;
                }

                this.showProgress(0);
                
                try {
                    for (let i = 0; i < validFiles.length; i++) {
                        await this.uploadImage(validFiles[i]);
                        this.showProgress((i + 1) / validFiles.length * 100);
                    }
                    
                    this.showMessage(`成功上传 ${validFiles.length} 张图片！`, 'success');
                } catch (error) {
                    this.showMessage('上传失败: ' + error.message, 'error');
                } finally {
                    this.hideProgress();
                }
            }

            async uploadImage(file) {
                const formData = new FormData();
                formData.append('image', file);

                const response = await fetch(`${this.apiBase}/upload`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '上传失败');
                }

                // 在编辑器中插入图片
                this.insertImageToEditor(result.data.url, result.data.original_name);
                return result;
            }

            insertImageToEditor(imageUrl, altText) {
                const workspace = document.getElementById('editorWorkspace');
                const img = document.createElement('img');
                img.src = `http://localhost:8080${imageUrl}`;
                img.alt = altText;
                img.className = 'image-preview';
                
                workspace.appendChild(img);
                workspace.appendChild(document.createElement('br'));
            }

            newArticle() {
                if (confirm('新建文章将清空当前内容，是否继续？')) {
                    this.currentArticle = null;
                    document.getElementById('articleTitle').value = '';
                    document.getElementById('articleSummary').value = '';
                    document.getElementById('articleAuthor').value = '';
                    document.getElementById('editorWorkspace').innerHTML = '<h1>新文章标题</h1><p>开始编写您的文章内容...</p>';
                    this.updateWordCount();
                    this.showMessage('新建文章成功', 'success');
                }
            }

            async saveArticle() {
                try {
                    const title = document.getElementById('articleTitle').value.trim();
                    const summary = document.getElementById('articleSummary').value.trim();
                    const author = document.getElementById('articleAuthor').value.trim();
                    const content = document.getElementById('editorWorkspace').innerHTML;

                    if (!title) {
                        this.showMessage('请输入文章标题', 'error');
                        return;
                    }

                    const articleData = {
                        title,
                        summary,
                        author: author || '匿名作者',
                        content,
                        word_count: this.getWordCount(),
                        created_at: new Date().toISOString(),
                        status: 'draft'
                    };

                    // 这里应该调用保存文章的API
                    // 暂时保存在本地存储中
                    this.saveToLocalStorage(articleData);
                    this.showMessage('文章保存成功！', 'success');
                    
                } catch (error) {
                    this.showMessage('保存失败: ' + error.message, 'error');
                }
            }

            previewArticle() {
                const title = document.getElementById('articleTitle').value.trim();
                const content = document.getElementById('editorWorkspace').innerHTML;
                
                if (!title || !content) {
                    this.showMessage('请先输入文章标题和内容', 'error');
                    return;
                }

                // 打开预览窗口
                const previewWindow = window.open('', '_blank');
                previewWindow.document.write(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <meta charset="UTF-8">
                        <title>${title} - 预览</title>
                        <style>
                            body { font-family: 'Microsoft YaHei', Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.8; }
                            h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
                            img { max-width: 100%; height: auto; border-radius: 8px; margin: 20px 0; }
                            p { margin: 15px 0; }
                        </style>
                    </head>
                    <body>
                        <h1>${title}</h1>
                        ${content}
                    </body>
                    </html>
                `);
            }

            loadArticles() {
                // 从本地存储加载文章列表
                const articles = JSON.parse(localStorage.getItem('articles') || '[]');
                this.renderArticleList(articles);
            }

            renderArticleList(articles) {
                const listContainer = document.getElementById('articleList');
                
                if (articles.length === 0) {
                    listContainer.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无文章</div>';
                    return;
                }

                listContainer.innerHTML = articles.map(article => `
                    <div class="article-item" onclick="editor.loadArticle('${article.id}')">
                        <div class="article-title">${article.title}</div>
                        <div class="article-meta">${new Date(article.created_at).toLocaleDateString('zh-CN')} | ${article.status === 'published' ? '已发布' : '草稿'}</div>
                    </div>
                `).join('');
            }

            loadArticle(articleId) {
                const articles = JSON.parse(localStorage.getItem('articles') || '[]');
                const article = articles.find(a => a.id === articleId);
                
                if (article) {
                    this.currentArticle = article;
                    document.getElementById('articleTitle').value = article.title;
                    document.getElementById('articleSummary').value = article.summary || '';
                    document.getElementById('articleAuthor').value = article.author || '';
                    document.getElementById('editorWorkspace').innerHTML = article.content;
                    this.updateWordCount();
                    this.showMessage('文章加载成功', 'success');
                }
            }

            saveToLocalStorage(articleData) {
                const articles = JSON.parse(localStorage.getItem('articles') || '[]');
                
                if (this.currentArticle) {
                    // 更新现有文章
                    const index = articles.findIndex(a => a.id === this.currentArticle.id);
                    if (index !== -1) {
                        articles[index] = { ...articles[index], ...articleData };
                    }
                } else {
                    // 创建新文章
                    articleData.id = Date.now().toString();
                    articles.unshift(articleData);
                    this.currentArticle = articleData;
                }
                
                localStorage.setItem('articles', JSON.stringify(articles));
                this.renderArticleList(articles);
            }

            autoSave() {
                if (this.currentArticle) {
                    this.saveArticle();
                }
            }

            updateWordCount() {
                const count = this.getWordCount();
                document.getElementById('wordCount').textContent = `字数: ${count}`;
            }

            getWordCount() {
                const content = document.getElementById('editorWorkspace').textContent;
                return content.replace(/\s+/g, ' ').trim().length;
            }

            showProgress(percent) {
                const progressBar = document.getElementById('progressBar');
                const progressFill = document.getElementById('progressFill');
                
                progressBar.style.display = 'block';
                progressFill.style.width = percent + '%';
                
                if (percent >= 100) {
                    setTimeout(() => this.hideProgress(), 500);
                }
            }

            hideProgress() {
                const progressBar = document.getElementById('progressBar');
                progressBar.style.display = 'none';
            }

            showMessage(text, type) {
                const message = document.createElement('div');
                message.className = `message ${type}`;
                message.textContent = text;
                document.body.appendChild(message);
                
                setTimeout(() => message.classList.add('show'), 100);
                setTimeout(() => {
                    message.classList.remove('show');
                    setTimeout(() => message.remove(), 300);
                }, 3000);
            }

            setStatus(text) {
                document.getElementById('statusText').textContent = text;
            }
        }

        // 初始化编辑器
        const editor = new ArticleEditor();

        // 页面加载完成提示
        window.addEventListener('load', () => {
            console.log('📝 Word风格图文编辑器已加载完成');
            console.log('📋 支持富文本编辑、图片上传、文章管理等功能');
        });
    </script>
</body>
</html>